<?php
class Response extends DOMDocument
{
	private $xhtml = true;
	
	public $header = null;
	
	/**
	 * Response Document (complete XHTML document)
	 *
	 * @param string $uri content uri
	 */
	public function __construct($name)
	{
		$map = Map::getInstance();
		$uri = $map->getURIByName($name);
		
		if ($uri) {
			if (isset($map[$uri]['index'])) {
				$index_uri = '/index/'.$map[$uri]['index'];
				
				$index_htm = new ResponseHTM($map[$index_uri]['name'],
					array(
						'doctype-system'=>'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd',
						'doctype-public'=>'-//W3C//DTD XHTML 1.0 Strict//EN',
						'omit-xml-declaration'=>'no',
						'indent'=>'no'
					)
				);
				
				$this->loadXML((string)$index_htm);
				
				// must be before includes
				$content_htm = new ResponseHTM($map[$uri]['name'],
					array(
						'omit-xml-declaration'=>'yes',
						'indent'=>'no'
					)
				);
				
				foreach ($map[$index_uri]['includes'] as $include) {
					$include_htm = new ResponseHTM($map[$include]['name'],
						array(
							'omit-xml-declaration'=>'yes',
							'indent'=>'no'
						),
						(isset($map[$include]['from'])?$content_htm->getData():null)
					);
					
					$this->appendNodes($map[$include]['id'], (string)$include_htm);
				}
				
				$this->appendNodes('content', (string)$content_htm);
			} else {
				$xhtml = (string)new ResponseHTM($map[$uri]['name'],
					array(
						'doctype-system'=>'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd',
						'doctype-public'=>'-//W3C//DTD XHTML 1.0 Strict//EN',
						'omit-xml-declaration'=>'no',
						'indent'=>'no'
					));
				if (empty($xhtml)) {
					$this->xhtml = false;
				}
				
				if ($this->xhtml) {
					$this->loadXML($xhtml);
				}
			}
		}
	}

	public function __toString()
	{
		if ($this->xhtml) {
			return $this->saveXML();
		} else {
			return '';
		}
	}
	
	/**
	 * Appends the XHTML data into the $this object ID
	 *
	 * @param string $id id to import
	 * @param string $from XHTML data to append
	 */
	private function appendNodes($id, $from)
	{
		$from_dom = new DOMDocument();
		$from_dom->loadXML('<root>'.$from.'</root>');
		
		$xp = new DomXPath($this);
		$id_dom = $xp->query("//*[@id = '".$id."']");
		
		if ($id_dom->length != 1) {
			throw new ElementaryException('Elementary: Found 0 or more than 1 id="'.$id.'" in index template.');
		} else {
			foreach ($from_dom->firstChild->childNodes as $item) {
				$id_dom->item(0)->appendChild($this->importNode($item, true));
			}
		}
	}
}